import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/views/report/model/salesman_report.dart';
import 'package:yuan_hang_app/views/report/widget/empty_widget.dart';
import '../../bean/user.dart';
import '../../http/api.dart';
import '../../http/http_utils.dart';
import '../../res/w_colors.dart';
import '../../res/w_constant.dart';
import '../../res/w_dimens.dart';
import '../../utils/common_utils.dart';
import '../../widget/custom_search.dart';
import '../../widget/label_item.dart';
import '../../widget/sort_content.dart';
import '../../widget/w_line.dart';
import '../../widget/w_list_view.dart';
import '../../widget/w_popup_window.dart';
import '../../widget/w_text.dart';
import '../../widget/w_toast.dart';

class SalesmanReportPage extends StatefulWidget {
  const SalesmanReportPage({super.key});

  @override
  BaseState<SalesmanReportPage> createState() => SalesmanReportPageState();
}

class SalesmanReportPageState extends BaseState<SalesmanReportPage> {
  Map sortParams = {};

  Map<String, dynamic> queryParams = {};

  List<SalesmanReport> dataList = [];

  Future<Null> _refresh() async {
    showLoading();
    fetchDataList();
  }

  var shopName = "";
  var checkTime = "";

  @override
  void initState() {
    super.initState();
    User user = WConstant().userInfo;
    shopName = user.shopName ?? "";
    queryParams["dealerId"] = user.shopId;
    //queryParams["dealerId"] = "10000289";
    queryParams["startTime"] = getSixDaysAgoDate();
    queryParams["endTime"] = getCurrentDate();

    checkTime = queryParams["startTime"]?.replaceAll("-", "/") +
        "-" +
        queryParams["endTime"]?.replaceAll("-", "/");

    sortParams["startTime"] = queryParams["startTime"];
    sortParams["endTime"] = queryParams["endTime"];
    fetchDataList();
  }

  void fetchDataList() {
    dataList = [];
    HttpUtils()
        .get(Api.getSaleManReportList, queryParams: queryParams)
        .then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          List data = value.data ?? [];
          List<SalesmanReport> list =
              data.map((item) => SalesmanReport.fromJson(item)).toList();
          dataList = list;
          setState(() {});
        }
      }
    });
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "销售顾问业绩统计报表",
      child: Column(
        children: [
          CustomSearch(
            hintText: "销售顾问名称",
            onSortClick: () {
              WPopupWindow.showSort(
                  context: context,
                  sortType: SortType.SALESMAN_REPORT,
                  sortParams: sortParams,
                  onSelected: (Map params) {
                    sortParams = params;
                    params.forEach((key, value) {
                      queryParams[key] = value;
                      if (queryParams.containsKey(key) && value == null) {
                        queryParams.remove(key);
                        queryParams["startTime"] = getSixDaysAgoDate();
                        queryParams["endTime"] = getCurrentDate();
                      }
                    });
                    if (queryParams["startTime"] != null &&
                        queryParams["endTime"] != null) {
                      checkTime =
                          queryParams["startTime"]?.replaceAll("-", "/") +
                              "-" +
                              queryParams["endTime"]?.replaceAll("-", "/");
                    }
                    setState(() {});
                    showLoading();
                    fetchDataList();
                  });
            },
            onTextChange: (text) {
              queryParams["salemanName"] = text;
              CommonUtils.antiShake(fetchDataList);
            },
          ),
          LabelItem(label: "直营店简称", value: shopName),
          LabelItem(label: "统计时间", value: checkTime),
          if (dataList.isEmpty)
            EmptyWidget(
              onTap: () {
                showLoading();
                fetchDataList();
              },
            ),
          if (dataList.isNotEmpty)
            Expanded(
              child: RefreshIndicator(
                  onRefresh: _refresh,
                  child: ListView.builder(
                    padding: EdgeInsets.only(top: 10.px),
                    itemBuilder: _listItem,
                    itemCount: dataList.length,
                  )),
            ),
        ],
      ),
    );
  }

  Widget _listItem(context, index) {
    SalesmanReport item = dataList[index];

    return Container(
      decoration: BoxDecoration(boxShadow: [
        BoxShadow(
            color: WColors.CDFEFFB,
            offset: const Offset(0, 1),
            blurRadius: 3.px)
      ], borderRadius: BorderRadius.circular(10.px), color: Colors.white),
      margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 10.px),
      padding: EdgeInsets.only(bottom: 10.px),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(height: 10.px),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                WLine(
                  height: 16.px,
                  width: 4.px,
                  color: WColors.primaryColor,
                ),
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 10.px),
                    child: WText(
                      item.title ?? "",
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: WDimens.tsLarge,
                          color: WColors.mainTextColor,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 5.px,
            ),
            _itemRow("线上线索量", "${item.onClueNum ?? ""}"),
            _itemRow("线下线索量", "${item.offClueNum ?? ""}"),
            _itemRow("市场活动线索量", "${item.marketingActivityNum ?? ""}"),
            _itemRow("合计线索量", "${item.clueNum ?? ""}"),
            _itemRow("排程数", "${item.scheduleNum ?? ""}"),
            _itemRow("排程率", "${item.scheduleRate ?? ""}%"),
            _itemRow("排程到店数", "${item.scheduleInShopNum ?? ""}"),
            _itemRow("排程到店率", "${item.scheduleInShopRate ?? ""}%"),
            _itemRow("试驾数", "${item.testDriveNum ?? ""}"),
            _itemRow("首触试驾率", "${item.testDriveRate ?? ""}%"),
            _itemRow("战败数", "${item.lostNum ?? ""}"),
            _itemRow("首触战败数", "${item.firstLostNum ?? ""}", isLast: true),
          ]),
    );
  }

  Widget _itemRow(title, fRate, {bool isLast = false}) {

    BoxDecoration leftDecoration = BoxDecoration(
        border: Border(
            left: BorderSide(color: WColors.CCCCCCC, width: 1.px),
            top: BorderSide(color: WColors.CCCCCCC, width: 1.px),
            right: BorderSide(color: WColors.CCCCCCC, width: 1.px)));
    BoxDecoration rightDecoration = BoxDecoration(
        border: Border(
            top: BorderSide(color: WColors.CCCCCCC, width: 1.px),
            right: BorderSide(color: WColors.CCCCCCC, width: 1.px)));
    if (isLast) {
      leftDecoration = BoxDecoration(
          border: Border.all(color: WColors.CCCCCCC, width: 1.px));
      rightDecoration = BoxDecoration(
          border: Border(
              bottom: BorderSide(color: WColors.CCCCCCC, width: 1.px),
              top: BorderSide(color: WColors.CCCCCCC, width: 1.px),
              right: BorderSide(color: WColors.CCCCCCC, width: 1.px)));
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 5.px),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            flex: 3,
            child: Container(
              padding: EdgeInsets.only(left: 5.px),
              decoration: leftDecoration,
              child: WText(
                title,
                style: TextStyle(
                    fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
              ),
            ),
          ),
          Expanded(
            flex: 2,
            child: Container(
              decoration: rightDecoration,
              alignment: Alignment.center,
              child: WText(
                _getFormattedRate(fRate),
                style: TextStyle(
                    fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _getFormattedRate(String fRate) {
    // 检查fRate是否包含百分号
    if (fRate.contains('%')) {
      // 移除百分号并尝试转换为小数
      String valueStr = fRate.replaceAll('%', '');
      double? value = double.tryParse(valueStr);

      // 检查是否为整数
      if (value != null && value == value.roundToDouble()) {
        // 返回整数部分并添加百分号
        return '${value.round()}%';
      }
    }
    // 如果不包含百分号或无法转换为整数，返回原始的fRate
    return fRate;
  }

  String getCurrentDate() {
    DateTime now = DateTime.now();
    return "${now.year.toString().padLeft(4, '0')}-${(now.month).toString().padLeft(2, '0')}-${(now.day).toString().padLeft(2, '0')}";
  }

  String getSixDaysAgoDate() {
    DateTime sixDaysAgo = DateTime.now().subtract(const Duration(days: 6));
    return "${sixDaysAgo.year.toString().padLeft(4, '0')}-${(sixDaysAgo.month).toString().padLeft(2, '0')}-${(sixDaysAgo.day).toString().padLeft(2, '0')}";
  }
}
